package lgkj.meicqt20.ui;

import android.app.Activity;
import android.content.Context;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import lgkj.meicqt20.utils.AllKindsOfConstant;
import lgkj.meicqt20.utils.CommUtils;
import lgkj.meicqt20.utils.HttpUtils;
import lgkj.meicqt20.utils.SharedPreferencesUtils;

/**
 * Created by Administrator on 2018/12/26 0026.
 */

public abstract class BaseActivity extends AppCompatActivity {
    /***获取TAG的activity名称**/
    protected String TAG = getClass().getSimpleName();
    protected SharedPreferencesUtils sharedPreferencesUtils;
    protected static List<Activity> activitiesList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        CommUtils.closeBar(BaseActivity.this);
        setContentView(setContentView());
        ButterKnife.bind(this);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        init();
        initData();
    }

    protected DifferentDislayActivity differentDislay;

    protected void displayDifferen() {

    }

    @Override
    protected void onStart() {
        super.onStart();
        try {
            DisplayManager manager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
            Display[] displays = manager.getDisplays();
            if (differentDislay == null) {
                differentDislay = new DifferentDislayActivity(this, displays[1]);
                differentDislay.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                differentDislay.show();
            }
        } catch (Exception e) {
            Log.e(TAG, "onStart: " + e.getMessage());
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (differentDislay != null)
            differentDislay.onStop();
    }

    public abstract int setContentView();

    public abstract void init();

    public abstract void initData();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return true;
    }


    //启动定位
    protected void statLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；
        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认GCJ02
        //GCJ02：国测局坐标；
        //BD09ll：百度经纬度坐标；
        //BD09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标

        option.setScanSpan(0);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，V7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明

        mLocationClient.start();
    }

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            Log.i(TAG, "onReceiveLocation: " + location.getLocType());
            double latitude = location.getLatitude();    //获取纬度信息
            double longitude = location.getLongitude();    //获取经度信息
            float radius = location.getRadius();    //获取定位精度，默认值为0.0f
            if (location.getLocType() == 161 || location.getLocType() == 61)
                getLocation(latitude + "", longitude + "");
        }
    }

    /**
     * 发送定位
     *
     * @param lat
     * @param lng
     */
    protected void getLocation(String lat, String lng) {
        Map<String, String> map = new HashMap<>();
        map.put("lng", lng);
        map.put("lat", lat);
        HttpUtils.getHttp(map, AllKindsOfConstant.getposition, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
            }

            @Override
            public void errorHttp(String msg) {

            }
        });
    }


    protected void bandViewInit(initBannersDataResult call) {
        if (banners.size() > 0) {
            call.resultSuccess(banners);
        } else {
            inittopBannersData(call);
        }
    }

    protected List<String> banners = new ArrayList<>();

    private void inittopBannersData(final initBannersDataResult call) {
        Map<String, String> params = new HashMap<>();
        params.put("area", "3");
        HttpUtils.getHttp(params, AllKindsOfConstant.PATH_ADVERTISEMENT, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                try {
                    String info = jsonObject.getString("info");
                    if (!"success".equals(info)) {
                        Log.i("path_two", "获取消息失败~~");
                    } else {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        Log.i("path_two", "广告的数量：  " + jsonArray.length());
                        banners.clear();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject json = (JSONObject) jsonArray.get(i);
                            String path = json.getString("ad_file");
//                            Log.i("path_two", "广告地址：   " + path);
                            banners.add(banners.size(), path);
                        }
                    }
                } catch (JSONException e) {
                    Log.i("path_two", e.toString());
                } finally {
                    call.resultSuccess(banners);
                }
            }

            @Override
            public void errorHttp(String msg) {

            }
        });
    }

    protected interface initBannersDataResult {
        void resultSuccess(List<String> list);
    }
}
